package com.example.payment.messaging.consumer;

import com.example.payment.messaging.message.OrderPaidMessage;
import com.example.payment.messaging.message.OrderStockReservedMessage;
import com.example.payment.messaging.producer.PaymentEventProducer;
import com.example.payment.service.PaymentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

/**
 * 订单库存预留成功事件消费者
 * 监听 order_stock_reserved Topic
 * 
 * @author mall-team
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OrderStockReservedConsumer {

    private final PaymentService paymentService;
    private final PaymentEventProducer paymentEventProducer;

    /**
     * 消费订单库存预留成功事件
     * 1. 模拟支付处理
     * 2. 发送订单支付成功事件
     * 
     * @param message 库存预留成功消息
     * @param ack 手动确认对象
     */
    @KafkaListener(topics = "order_stock_reserved", groupId = "payment-service-group")
    public void handleOrderStockReserved(OrderStockReservedMessage message, Acknowledgment ack) {
        log.info("收到订单库存预留成功事件: orderNo={}, userId={}, totalAmount={}", 
            message.getOrderNo(), message.getUserId(), message.getTotalAmount());
        
        try {
            // 1. 模拟支付处理
            String paymentNo = paymentService.processPayment(
                    message.getOrderNo(),
                    message.getUserId(),
                    message.getTotalAmount()
            );
            
            log.info("支付处理成功: orderNo={}, paymentNo={}", message.getOrderNo(), paymentNo);
            
            // 2. 构建订单支付成功消息
            OrderPaidMessage paidMessage = OrderPaidMessage.builder()
                    .orderNo(message.getOrderNo())
                    .paymentNo(paymentNo)
                    .amount(message.getTotalAmount())
                    .paymentTime(System.currentTimeMillis())
                    .build();
            
            // 3. 发送订单支付成功事件
            paymentEventProducer.sendOrderPaidEvent(paidMessage);
            
            // 4. 手动确认消息
            ack.acknowledge();
            log.info("订单库存预留成功事件处理完成: orderNo={}", message.getOrderNo());
            
        } catch (Exception e) {
            log.error("处理订单库存预留成功事件失败: orderNo={}, error={}", 
                message.getOrderNo(), e.getMessage(), e);
            // 不确认消息，等待重试
            // 实际生产环境中可能需要更复杂的重试和死信队列机制
        }
    }
}

